package com.bilin.coin.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.bilin.coin.ApiConstant;
import com.bilin.coin.R;
import com.bilin.coin.bean.CommonSuccessEvent;
import com.bilin.coin.common.base.BaseAppCompatActivity;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.InvocationTargetException;

import butterknife.BindView;


/**
 * Created by LG on 2017/3/18.
 */
@Route(path = "/mall/WebLiveActivity")
public class WebLiveActivity extends BaseAppCompatActivity {


    @BindView(R.id.pb_loading)
    ProgressBar pbLoading;
    @BindView(R.id.wv_details)
    WebView wvDetails;

    @Autowired
    String title;

    @Autowired
    String url;

    @Autowired
    int type;//0：title原来的样子 1:title变白 状态栏也变白

    @Override
    protected void initView() {
        setTitle(title);
        if (type == 1) {
            //根据状态栏颜色来决定状态栏文字用黑色还是白色
         /*   StatusBarUtil.setStatusBarMode(WebLiveActivity.this, true, R.color.colorWhiteMain);
            mToolbar.setNavigationIcon(R.drawable.ic_chevron_left_black2_24dp);
            mToolbar.setBackgroundColor(getResources().getColor(R.color.colorWhiteMain));
            mTvTitle.setTextColor(getResources().getColor(R.color.black333));*/
        }
    }

    @Override
    protected void initData() {

        wvDetails.setVisibility(View.GONE);
        //url= GdproApplication.strH5Url+"";
        wvDetails.getSettings().setLoadWithOverviewMode(true);
        wvDetails.getSettings().setJavaScriptEnabled(true);
        wvDetails.getSettings().setBlockNetworkImage(false);//解决图片不显示
        //wvDetails.getSettings().setBuiltInZoomControls(true);
        wvDetails.getSettings().setLoadsImagesAutomatically(true);
        wvDetails.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        wvDetails.getSettings().setUseWideViewPort(true);//扩大比例的缩放
        wvDetails.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);

        wvDetails.getSettings().setDomStorageEnabled(true);
        wvDetails.requestFocus();
        wvDetails.getSettings().setSupportZoom(true); // 设置可以支持缩放
        wvDetails.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); // 不加载缓存内容

        wvDetails.getSettings().setMediaPlaybackRequiresUserGesture(false);
        if (Build.VERSION.SDK_INT < 8) {
            //wvDetails.getSettings().setPluginsEnabled(true);
        } else {
            wvDetails.getSettings().setPluginState(WebSettings.PluginState.ON);
        }
        //允许混合模式（http与https）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            wvDetails.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        wvDetails.getSettings().setAllowFileAccess(true);
        wvDetails.getSettings().setAllowFileAccessFromFileURLs(true);

        wvDetails.setWebViewClient(new WebViewClient() {

            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (!url.startsWith("http:") ||!url.startsWith("https:")) {
                    if (url.startsWith("alipay")) {
                        Intent intent = new Intent(Intent.ACTION_VIEW,
                                Uri.parse(url));
                        startActivity(intent);
                        return true;
                    } else {
                        return false;
                    }
                   /* Intent intent = new Intent(Intent.ACTION_VIEW,
                            Uri.parse(url));
                    startActivity(intent);
                    return true;*/
                }
                wvDetails.loadUrl(url);
                return true;
            }

            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

            }
        });
        wvDetails.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress == 100) {
                    pbLoading.setProgress(newProgress);
                    pbLoading.setVisibility(View.GONE);
                    wvDetails.setVisibility(View.VISIBLE);
                } else {
                    pbLoading.setProgress(newProgress);
                    pbLoading.setVisibility(View.VISIBLE);
                    wvDetails.setVisibility(View.GONE);
                }
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if (type == 1) {
                    if (title.length() > 12) {
                        setTitle(title.substring(0,10)+"...");
                    } else {
                        setTitle(title);
                    }
                }
            }
        });
        if (type == 1) {
            wvDetails.addJavascriptInterface(new JSInterface1(), "client");
        }
        wvDetails.loadUrl(url);
    }

    class JSInterface1 {
        //JavaScript调用此方法
        @JavascriptInterface
        public void jump(String id) {
            baseStartActivityWith("/mall/ProductDetailActivity")
                    .withString("id",id)
                    .withInt("level", 1)
                    .navigation();
        }
    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_webh5_loading;
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && wvDetails.canGoBack()) {
            wvDetails.goBack();// 返回前一个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


   /* private static final int SDK_PAY_FLAG = 1;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    *//**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     *//*
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        //showAlert(PayDemoActivity.this, getString(R.string.pay_success) + payResult);
                        //showToast("支付成功 " + payResult.toString());
                        Log.e("aliPay", payResult.toString());
                        //getPayResult();
                        paySuccessDialog();
                        EventBus.getDefault().post(new PaySuccessEvent());
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        //showAlert(PayDemoActivity.this, getString(R.string.pay_failed) + payResult);
                        //showToast("支付失败 " + payResult.toString());
                        //Log.e("aliPay", payResult.toString());
                        payErrorDialog(payResult.toString());
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };*/

    @Override
    protected void onPause() {
        super.onPause();
        try {
            wvDetails.getClass().getMethod("onPause").invoke(wvDetails,  (Object[])null);
        } catch (IllegalAccessException e) {

        } catch (InvocationTargetException e) {e.printStackTrace();
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        if (ApiConstant.LIVE_URL.equals(url)) {
            EventBus.getDefault().post(new CommonSuccessEvent(CommonSuccessEvent.SwitchTab));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            wvDetails.getClass().getMethod("onResume").invoke(wvDetails,(Object[])null);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

}
